//
//  CouponsViewController.m
//  HTP
//
//  Created by 王鑫 on 15/11/28.
//  Copyright © 2015年 nit. All rights reserved.
//

#import "MyCouponsViewController.h"

//TableCell
#import "MyCouponsTableViewCell.h"

//Model
#import "MyCouponsVIewModel.h"

#define CELLH ScreenWidth * 1 / 3
#define LENGHT 10

@interface MyCouponsViewController () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic,strong) UITableView *couponsTableView;

@property (nonatomic,strong) UILabel *messageLabel;
//筛选后卡卷
@property (nonatomic,strong) NSMutableArray *couponsArray;

@property (nonatomic,strong) UIView *messageView;
//获取到的卡卷
@property (nonatomic,strong) NSMutableArray *messageArray;

@property int flag;
@end

@implementation MyCouponsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.couponsTableView];
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self showGetData];
    [self initNav];
}

//TODO: 导航栏UI初始化
- (void)initNav {
    [self addCustomTitleWithTitle:@"我的优惠劵"];
    [self addCustomBackBase];
}

//TODO: get方法重写
- (UITableView *)couponsTableView {
    if (!_couponsTableView) {
        _couponsTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeihgt -NavHe) style:UITableViewStyleGrouped];
        _couponsTableView.delegate = self;
        _couponsTableView.dataSource = self;
        _couponsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _couponsTableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_qianbao"]];
        _couponsTableView.tableHeaderView = self.messageView;
        //上拉设置
        _couponsTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footRefresh)];
        //下拉设置
        _couponsTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headRefresh)];
    }
    return _couponsTableView;
}


//TODO: tableView代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [_couponsArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *idendef = @"Identifier";
    MyCouponsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:idendef];
    if (!cell) {
        cell = [[MyCouponsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:idendef];
    }
    [cell setData:[_couponsArray objectAtIndex:indexPath.section]];
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return CELLH;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 7;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 8;
}

//TODO: head显示部分

- (UIView *)messageView {
    if (!_messageView) {
        _messageView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 30)];
        _messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, ScreenWidth - 10, 30)];
        _messageLabel.textColor = RGBCOLOR(100, 100, 100, 1);
        _messageLabel.font = [UIFont systemFontOfSize:14];
        
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"有%ld个优惠劵即将过期",[_couponsArray count]]];
        NSInteger length = [NSString stringWithFormat:@"有%ld个优惠劵即将过期",[_couponsArray count]].length;
        [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(1, length - 9)];
        _messageLabel.attributedText = str;
        [_messageView addSubview:_messageLabel];
    }

    return _messageView;
}

//TODO: 上拉加载数据
- (void)footRefresh {
    _flag = 1;
    if (_couponsArray == nil || _couponsArray.count == 0) {
        [self getCouponsInfo:0 withLenght:LENGHT];
    } else {
        [self getCouponsInfo:[_couponsArray count] withLenght:LENGHT];
    }
}

- (void)endFootRefresh {
    switch (self.couponsTableView.mj_footer.state) {
        case MJRefreshStateRefreshing:
            [self.couponsTableView.mj_footer endRefreshing];
            break;
        default:
            break;
    }
}

//TODO: 下拉刷新数据
- (void)headRefresh {
    _flag = 2;
    if (_couponsArray == nil || _couponsArray.count == 0) {
        [self getCouponsInfo:0 withLenght:LENGHT];
    }else {
        [self getCouponsInfo:0 withLenght:[_couponsArray count]];
    }
}

- (void)endHeadRefresh {
    switch (self.couponsTableView.mj_header.state) {
        case MJRefreshStateRefreshing:
            [self.couponsTableView.mj_header endRefreshing];
            break;
        default:
            break;
    }
}

//TODO: 刚进入时的数据加载
- (void)showGetData{
    _flag = 0;
    if (_messageArray == nil || _messageArray.count == 0) {
        [self getCouponsInfo:0 withLenght:LENGHT];
        return;
    }
    [self.couponsTableView.mj_header beginRefreshing];
}


//TODO: 获得数据

- (void)getCouponsInfo:(NSInteger) start withLenght:(NSInteger) lenght {
    MyCouponsVIewModel *myCouponsVM = [[MyCouponsVIewModel alloc] init];
    [myCouponsVM setBlockWithReturnBlock:^(id returnValue) {
        [self hiddenMbProgress];
        
        [self modelOfDic:returnValue];
        [self screenInfoWithLenght:start + lenght];
        
        [self.couponsTableView reloadData];
    } WithErrorBlock:^(id errorCode) {
        [self hiddenMbProgress];
    } WithFailureBlock:^{
        [self hiddenMbProgress];
    }];
    [self showMbProgress:@""];
    [myCouponsVM getCouponsInfoByuserId:[USERCONTENT getUserId]];
}

//TODO: 数据处理

//字典 -> 模型

- (void)modelOfDic:(NSDictionary *)message{
    DLog(@"%@",message[INTERFACE_INFO]);
    _messageArray = [MyCouponsModel mj_objectArrayWithKeyValuesArray:message[INTERFACE_INFO]];
}

//数据筛选（选出可用卡卷,加载的卡卷）

- (void)screenInfoWithLenght:(NSInteger) lenght {
    
    _couponsArray = [[NSMutableArray alloc] init];
    
    for (MyCouponsModel *couponInfo in _messageArray) {
        if ([couponInfo.isUsed intValue] == 0 && [couponInfo.status intValue] == 0) {
            [_couponsArray addObject:couponInfo];
        }
    }
    
    if ([_couponsArray count] >= lenght) {
        _couponsArray = [NSMutableArray arrayWithArray:[_couponsArray subarrayWithRange:NSMakeRange(0, lenght)]];
    }else
        _couponsArray = [NSMutableArray arrayWithArray:[_couponsArray subarrayWithRange:NSMakeRange(0, [_couponsArray count])]];
    if (_flag == 1) {
        [self endFootRefresh];
    }else if (_flag == 2) {
        [self endHeadRefresh];
    }
    
    //显示卡卷数
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"有%ld个优惠劵即将过期",[_couponsArray count]]];
    NSInteger length = [NSString stringWithFormat:@"有%ld个优惠劵即将过期",[_couponsArray count]].length;
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(1, length - 9)];
    _messageLabel.attributedText = str;
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
